import { createRouter, createWebHashHistory } from 'vue-router';
import { useAuthStore } from '@/stores/authStore';
function showLoginModal() {
  const authStore = useAuthStore();
  authStore.showLoginModal(); 
}
// 定义路由 
const routes = [
  {
    path: '/',
    name: 'Home',
    redirect: '/reportLibrary', // 重定向到子路由
    component: () => import('@/views/Home/index.vue'),  // 动态导入组件 
    children: [
      {
        path: 'reportLibrary', // 老师报告库子路由路径 
        name: 'ReportLibrary',
        component: () => import('@/views/ReportLibrary/index.vue'),  // 子路由组件 
      },
      {
        path: 'reportManagement', // 老师报告管理子路由路径 
        name: 'ReportManagement',
        component: () => import('@/views/ReportManagement/index.vue'),  // 子路由组件 
      },
      {
        path: 'myReport', // 子路由路径 
        name: 'MyReport',
        component: () => import('@/views/MyReport/index.vue'),  // 子路由组件 
        meta: { keepAlive: true }
      },
    ],
  },
  {
    path: '/reportDetail',
    name: 'ReportDetail',
    component: () => import('@/views/ReportDetail/index.vue'),  // 
  },
  {
    path: '/editor',
    name: 'Editor',
    component: () => import('@/views/Editor/index.vue'),  //  
    meta: { login: true }
  }
];

// 创建路由实例 
const router = createRouter({
  // history: createWebHistory(),
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  console.log('路由变化:', to, from);
  if(to.query.token){ // 从url中获取token
    localStorage.setItem('token',to.query.token)
  }
  const token = localStorage.getItem('token');
  console.log(to.meta.login);
  
  if (!token && !to.meta.login) {
    showLoginModal()
    next(); 
  } else {
    next(); // 允许页面跳转 
  }
});
export default router;